<template>
  <div>
    <n-spin :show="isloading">
      <template #description>
        <span>设备升级中, 请不要有任何操作, 否则可能造成设备损坏, 请耐心等待...</span>
      </template>
      <n-card>
        <n-card title="设备信息" :bordered="false">
          <n-form label-width="120px" label-placement="left">
            <n-form-item label="设备类型" :required="true"
              ><span>{{ deviceType }}</span></n-form-item
            >
            <n-form-item label="软件版本" :required="true"
              ><span>{{ version }}</span></n-form-item
            >
            <!-- <n-form-item label="传输距离: "><span></span></n-form-item> -->
            <n-form-item label="最大跳数" :required="true"
              ><span>{{ maxHopNum }} 跳</span></n-form-item
            >
            <n-form-item label="最大节点数" :required="true"
              ><span>{{ maxNodeNum }} 节点</span></n-form-item
            >
            <n-form-item label="最大传输距离" :required="true"
              ><span>{{ rangeMode }} 公里</span></n-form-item
            >
          </n-form>
        </n-card>
        <n-card title="软件升级" :bordered="false">
          <n-upload
            ref="uploadRef"
            :default-upload="false"
            @change="handleChange"
            :max="1"
            accept=".tar.gz, application/gzip, application/x-gzip"
            :custom-request="customRequest"
            @finish="handleOnFinsh"
            @error="handleOnError"
            abstract
          >
            <n-button-group>
              <n-upload-trigger #="{ handleClick }" abstract>
                <n-button color="#E0531f" @click="handleClick">选择软件升级包</n-button>
              </n-upload-trigger>
              <n-button type="primary" :disabled="!fileListLengthRef" @click="handleUpdateClick"
                >软件升级</n-button
              >
            </n-button-group>
            <n-upload-file-list />
          </n-upload>
        </n-card>
        <n-card title="网页 升级" :bordered="false">
          <n-upload
            ref="webUploadRef"
            :max="1"
            accept=".zip"
            :default-upload="false"
            @change="handleWebChange"
            :custom-request="customWebRequest"
            @finish="handleWebOnFinsh"
            @error="handleWebOnError"
            abstract
          >
            <n-button-group>
              <n-upload-trigger #="{ handleClick }" abstract>
                <n-button color="#E0531f" @click="handleClick">选择网页升级包</n-button>
              </n-upload-trigger>
              <n-button
                type="primary"
                :disabled="!webfileListLengthRef"
                @click="handleWebUpdateClick"
                >软件升级</n-button
              >
            </n-button-group>
            <n-upload-file-list />
          </n-upload>
        </n-card>
      </n-card>
    </n-spin>
  </div>
</template>

<script lang="ts" setup>
  import { useDeviceInfoStore } from '@/store/modules/deviceInfo';
  import { computed, onMounted, ref } from 'vue';
  import { getConfig } from '@/api/config';
  import type { UploadFileInfo, UploadInst, UploadCustomRequestOptions } from 'naive-ui';
  import { createAlova } from 'alova';
  import adapterFetch from 'alova/fetch';
  import { useMessage } from 'naive-ui';

  const message = useMessage();

  const isloading = ref<boolean>(false);

  const deviceInfoStore = useDeviceInfoStore();

  const deviceType = computed(() => deviceInfoStore.getDeviceType);
  const version = computed(() => deviceInfoStore.getVersion);
  const maxHopNum = computed(() => deviceInfoStore.getMaxHopNum);
  const maxNodeNum = computed(() => deviceInfoStore.getMaxNodeNum);

  const rangeMode = ref<string>('');

  /********************************软件升级**************************************/
  const fileListLengthRef = ref(0);
  const uploadRef = ref<UploadInst | null>(null);

  function handleChange(options: { fileList: UploadFileInfo[] }) {
    fileListLengthRef.value = options.fileList.length;
  }

  function handleUpdateClick() {
    uploadRef.value?.submit();
  }

  function customRequest(options: UploadCustomRequestOptions) {
    // console.log(options);
    isloading.value = true;

    const { file, onProgress, onError, onFinish } = options;

    // 检查文件是否存在
    if (!file.file) {
      return;
    }
    //创建FormData对象
    const formData = new FormData();
    formData.append('file', file.file);

    const url =
      import.meta.env.VITE_GLOB_UPLOAD_URL === '/upload'
        ? import.meta.env.VITE_GLOB_UPLOAD_URL
        : `http://${window.location.hostname}${import.meta.env.VITE_GLOB_UPLOAD_URL}`;

    //创建Alova实例
    const alovaInstance = createAlova({
      baseURL: '',
      cacheFor: null,
      responded: {
        onSuccess: (response) => response.statusText,
      },
      requestAdapter: adapterFetch(),
    });
    alovaInstance
      .Post(url, formData)
      .send()
      .then((result) => {
        if (result === 'OK') {
          //isloading.value = false;
          message.success('软件上传成功, 开始升级!');
          const alovaInstanceUpdate = createAlova({
            baseURL: '',
            cacheFor: null,
            responded: {
              onSuccess: (response) => response.statusText,
            },
            requestAdapter: adapterFetch(),
          });
          alovaInstanceUpdate
            .Get('/update')
            .send()
            .then((result) => {
              if (result === 'OK') {
                if (fileListLengthRef.value > 0) {
                  onProgress({ percent: 1 });
                  onFinish();
                  isloading.value = false;
                  message.success('设备升级成功!');
                }
              } else {
                onError();
                isloading.value = false;
                message.error('设备升级失败');
              }
            })
            .catch(() => {
              isloading.value = false;
              message.error('设备升级失败');
            });
        } else {
          onError();
          isloading.value = false;
          message.error('软件上传失败');
        }
      })
      .catch((err) => {
        // console.log(err);
        if (fileListLengthRef.value > 0) {
          onError();
        }
        isloading.value = false;
        message.error('软件上传失败');
      });
  }

  function handleOnFinsh({ file }) {
    //console.log(file);
    fileListLengthRef.value = 0;
    if (uploadRef.value) {
      uploadRef.value.clear();
    }
  }

  function handleOnError({ file }) {
    fileListLengthRef.value = 0;
    if (uploadRef.value) {
      uploadRef.value.clear();
    }
  }
  /**********************************end****************************************/
  const webfileListLengthRef = ref(0);
  const webUploadRef = ref<UploadInst | null>(null);

  function handleWebChange(options: { fileList: UploadFileInfo[] }) {
    webfileListLengthRef.value = options.fileList.length;
  }

  function customWebRequest(options: UploadCustomRequestOptions) {
    // console.log(options);
    isloading.value = true;

    const { file, onProgress, onError, onFinish } = options;

    // 检查文件是否存在
    if (!file.file) {
      return;
    }
    //创建FormData对象
    const formData = new FormData();
    formData.append('webfile', file.file);

    //创建Alova实例
    const alovaInstance = createAlova({
      baseURL: '',
      cacheFor: null,
      responded: {
        onSuccess: (response) => response.statusText,
      },
      requestAdapter: adapterFetch(),
    });
    alovaInstance
      .Post('/webupload', formData)
      .send()
      .then((result) => {
        if (result === 'OK') {
          //isloading.value = false;
          message.success('网页升级成功!');
          onProgress({ percent: 1 });
          onFinish();
          isloading.value = false;
        } else {
          onError();
          isloading.value = false;
          message.error('网页升级失败!');
        }
      })
      .catch((err) => {
        // console.log(err);
        onError();
        isloading.value = false;
        message.error('网页升级失败');
      });
  }

  function handleWebUpdateClick() {
    webUploadRef.value?.submit();
  }

  function handleWebOnFinsh() {
    webfileListLengthRef.value = 0;
    if (webUploadRef.value) {
      webUploadRef.value.clear();
    }
  }
  function handleWebOnError() {
    webfileListLengthRef.value = 0;
    if (webUploadRef.value) {
      webUploadRef.value.clear();
    }
  }

  onMounted(async () => {
    const config = await getConfig();
    rangeMode.value = config.rangeMode;
  });
</script>
